import requests
import os
from PyQt5.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QFileDialog, QPushButton
from PyQt5.QtGui import QFont  # 新增字体支持
from PyQt5.QtCore import Qt  # 新增对齐方式支持
from .video_input import VideoInput
from .type_selector import TypeSelector
from .progress import ProgressBar
from .result_display import ResultDisplay
from PyQt5.QtCore import QTimer 
from ..services.crawler_service import CrawlerService

class MainWindow(QMainWindow):
    def __init__(self, api_client):
        super().__init__()
        self.api_client = api_client
        self.current_progress = 0
        self.setup_ui()
        
    def setup_ui(self):
        self.setStyleSheet("""
            /* 主窗口样式 */
            QMainWindow {
                background-color: #f0f2f5;
                font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            }
            
            /* 中心部件样式 */
            QWidget#centralWidget {
                background-color: #ffffff;
                border-radius: 12px;
                margin: 15px;
                padding: 20px;
                border: 1px solid #e0e3e7;
            }
            
            /* 标签样式 */
            QLabel {
                font-size: 14px;
                color: #3a3f45;
                margin-bottom: 5px;
            }
            
            /* 按钮基础样式 */
            QPushButton {
                background-color: #4e97cd;
                color: white;
                border: none;
                padding: 8px 16px;
                font-size: 14px;
                border-radius: 6px;
                min-width: 100px;
            }
            
            QPushButton:hover {
                background-color: #3d85c0;
            }
            
            QPushButton:pressed {
                background-color: #2c74b3;
            }
            
            /* 获取按钮特殊样式 */
            QPushButton#btn_fetch {
                background-color: #4CAF50;
            }
            
            QPushButton#btn_fetch:hover {
                background-color: #43A047;
            }
            
            QPushButton#btn_fetch:pressed {
                background-color: #388E3C;
            }
            
            /* 清除按钮特殊样式 */
            QPushButton#btn_clear {
                background-color: #f44336;
            }
            
            QPushButton#btn_clear:hover {
                background-color: #E53935;
            }
            
            QPushButton#btn_clear:pressed {
                background-color: #D32F2F;
            }
            
            /* 下载按钮特殊样式 */
            QPushButton#btn_download {
                background-color: #FF9800;
            }
            
            QPushButton#btn_download:hover {
                background-color: #FB8C00;
            }
            
            QPushButton#btn_download:pressed {
                background-color: #F57C00;
            }
            
            /* 输入框样式 */
            QLineEdit {
                padding: 10px;
                border: 1px solid #d1d5db;
                border-radius: 6px;
                font-size: 14px;
                background-color: #f9fafb;
                selection-background-color: #4e97cd;
                selection-color: white;
            }
            
            QLineEdit:focus {
                border: 1px solid #4e97cd;
                background-color: white;
            }
            
            /* 下拉框样式 */
            QComboBox {
                padding: 8px;
                border: 1px solid #d1d5db;
                border-radius: 6px;
                min-width: 120px;
                background-color: #f9fafb;
            }
            
            QComboBox:hover {
                border: 1px solid #c4c9d2;
            }
            
            QComboBox:on {
                border: 1px solid #4e97cd;
            }
            
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 20px;
                border-left-width: 1px;
                border-left-color: #d1d5db;
                border-left-style: solid;
                border-top-right-radius: 6px;
                border-bottom-right-radius: 6px;
            }
            
            /* 进度条样式 */
            QProgressBar {
                border: 1px solid #d1d5db;
                border-radius: 6px;
                text-align: center;
                background-color: #f0f3f7;
                height: 20px;
            }
            
            QProgressBar::chunk {
                background-color: #4e97cd;
                border-radius: 5px;
                width: 10px;
            }
            
            /* 结果显示区域样式 */
            QTextEdit {
                border: 1px solid #e0e3e7;
                border-radius: 6px;
                padding: 10px;
                background-color: #f9fafb;
                font-family: 'Consolas', 'Courier New', monospace;
                font-size: 13px;
            }
            
            /* 分隔线样式 */
            QFrame[frameShape="4"] { /* HLine */
                border: none;
                border-top: 1px solid #e0e3e7;
                margin: 10px 0;
            }
        """)
        self.setWindowTitle("视频分析客户端")
        self.setGeometry(100, 100, 800, 600)
        
        # 中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        layout = QVBoxLayout()
        central_widget.setLayout(layout)
        
        # 初始化各组件
        self.type_selector = TypeSelector(self.api_client)
        self.video_input = VideoInput()
        self.progress_bar = ProgressBar()
        self.result_display = ResultDisplay()
        
        # 添加组件到布局
        layout.addLayout(self.type_selector)
        layout.addLayout(self.video_input)
        layout.addWidget(self.progress_bar)
        layout.addWidget(self.result_display)
        
        # 连接信号
        self.video_input.btn_fetch.clicked.connect(self.handle_fetch)
        self.video_input.btn_clear.clicked.connect(self.handle_clear)

        # 在布局中添加下载按钮
        self.video_input.btn_download = QPushButton("下载视频")  # 新增下载按钮
        self.video_input.addWidget(self.video_input.btn_download)
        self.video_input.btn_download.clicked.connect(self.handle_download)  # 连接下载信号
    
    def handle_fetch(self):
        """处理获取视频数据请求"""
        video_url = self.video_input.get_url()
        selected_type = self.type_selector.get_selected_type()
        
        if not selected_type:
            self.result_display.show_warning("请选择视频类型")
            return
            
        if not video_url:
            self.result_display.show_warning("请输入视频地址")
            return
            
        self.progress_bar.start_progress()
        self.result_display.clear()
        
        self._handle_local_crawl(video_url, selected_type)
        # 根据类型选择处理方式
        # if selected_type['id'] in [1, 23]:
        #     self._handle_local_crawl(video_url, selected_type)
        # else:
        #     self._handle_api_fetch(video_url, selected_type)
    
    def _handle_local_crawl(self, video_url, video_type):
        try:
            # 初始化进度
            self.current_progress = 0  
            self.progress_bar.setValue(0)

            # 调用爬取服务
            result = CrawlerService.crawl_by_type(video_type, video_url)

            if not result['success']:
                    raise Exception(result.get('error', '爬取失败'))
            
            # 保存结果以便后续下载
            self.current_video_info = result
                
            
            # 更新进度
            for i in range(5):
                self.current_progress += 20
                self.progress_bar.setValue(self.current_progress)
                
            # 格式化结果显示
            self.show_crawl_result({
                'title': result.get('title', '未知标题'),
                'url': video_url,
                'type': result['type'],
                'source': result['platform'],
                'download_urls': [result['download_url']] if 'download_url' in result else []
            })
            
        except Exception as e:
            self.result_display.show_error(f"本地爬取失败: {str(e)}")
        finally:
            self.video_input.btn_fetch.setEnabled(True)
            self.video_input.btn_clear.setEnabled(True)
            self.progress_bar.reset()

    def handle_download(self):
        """处理视频下载"""
        if not hasattr(self, 'current_video_info') or not self.current_video_info.get('download_url'):
            self.result_display.show_warning("没有可下载的视频或未获取下载链接")
            return
        
        download_type = self.current_video_info.get('type')
        print("下载类型: ", download_type)
        # 获取下载URL信息
        download_info = self.current_video_info['download_url']
        
        # 如果是图片类型但URL是字符串，则当作视频处理
        if download_type != 'video' and isinstance(download_info, str):
            download_type = 'video'

        # 处理图片下载（download_info是字典或列表的情况）
        if download_type != 'video' and (isinstance(download_info, (dict, list))):
            # 如果是列表，转换为字典
            if isinstance(download_info, list):
                # 尝试从URL中提取有意义的文件名，否则使用image_1, image_2等
                download_info = {
                    url.split('/')[-1].split('!')[0].split('.')[0] or f"image_{i+1}": url 
                    for i, url in enumerate(download_info)
                }
            self._handle_image_download(download_info)
            return
        
        # 处理视频下载（download_info是字符串的情况）
        self._handle_video_download(download_info)

    # 下载视频
    def _handle_video_download(self, video_url):
        """处理单个视频下载"""
        # 让用户选择保存路径
        options = QFileDialog.Options()
        default_filename = f"{self.current_video_info.get('title', 'video')}.mp4"
        file_path, _ = QFileDialog.getSaveFileName(
            self, 
            "保存视频文件", 
            default_filename, 
            "MP4 Files (*.mp4);;All Files (*)", 
            options=options
        )
        
        if not file_path:
            return
        
        try:
            # 下载前准备
            self.result_display.append(f"\n开始下载视频到: {file_path}")

            # 设置进度条样式 - 视频使用绿色系
            self.progress_bar.setStyleSheet("""
                QProgressBar {
                    border: 2px solid #2e7d32;
                    border-radius: 8px;
                    text-align: center;
                    background-color: #e8f5e9;
                    height: 24px;
                }
                QProgressBar::chunk {
                    background-color: #4caf50;
                    border-radius: 6px;
                    width: 10px;
                }
            """)
            
            # 初始化进度条
            self.progress_bar.reset()
            self.progress_bar.setMinimum(0)
            self.progress_bar.setMaximum(100)
            self.progress_bar.setValue(0)
            self.progress_bar.setVisible(True)
            self.progress_bar.repaint()
            
            # 开始下载
            response = requests.get(video_url, stream=True)
            response.raise_for_status()
            
            total_size = int(response.headers.get('content-length', 0))
            downloaded = 0
            
            # 使用QApplication.processEvents()来强制UI更新
            from PyQt5.QtWidgets import QApplication
            
            # 写入文件
            with open(file_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)
                        downloaded += len(chunk)
                        
                        # 计算进度
                        progress = int((downloaded / total_size) * 100) if total_size > 0 else 0
                        
                        # 更新进度条
                        self.progress_bar.setValue(progress)
                        
                        # 强制处理UI事件
                        QApplication.processEvents()
            
            # 下载完成
            self.progress_bar.setValue(100)
            self.result_display.append(f"视频下载完成: {file_path}")
            
        except Exception as e:
            self.result_display.show_error(f"视频下载失败: {str(e)}")
            self.progress_bar.reset()
            if os.path.exists(file_path):
                os.remove(file_path)



    #下载图片
    def _handle_image_download(self, image_dict):
        """处理多个图片下载，带进度条显示"""
        # 让用户选择保存目录
        dir_path = QFileDialog.getExistingDirectory(self, "选择图片保存目录")
        if not dir_path:
            return
        
        try:
            total_images = len(image_dict)
            if total_images == 0:
                self.result_display.show_warning("没有可下载的图片")
                return
            
            # 设置进度条样式 - 图片使用紫色系
            self.progress_bar.setStyleSheet("""
                QProgressBar {
                    border: 2px solid #6a1b9a;
                    border-radius: 8px;
                    text-align: center;
                    background-color: #f3e5f5;
                    height: 24px;
                }
                QProgressBar::chunk {
                    background-color: #9c27b0;
                    border-radius: 6px;
                    width: 10px;
                }
            """)
            
            # 初始化双进度条（总进度和单文件进度）
            self.progress_bar.reset()
            self.progress_bar.setMinimum(0)
            self.progress_bar.setMaximum(100)
            self.progress_bar.setValue(0)
            self.progress_bar.setVisible(True)
            
            from PyQt5.QtWidgets import QApplication
            success_count = 0
            
            self.result_display.append(f"\n开始下载 {total_images} 张图片...")
            
            for index, (name, url) in enumerate(image_dict.items(), 1):
                # 处理文件名
                if not name.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
                    name += '.jpg'
                
                file_path = os.path.join(dir_path, name)
                
                # 更新总进度文本
                self.result_display.append(f"正在下载 ({index}/{total_images}): {name}")
                
                try:
                    # 下载单个图片（带进度）
                    response = requests.get(url, stream=True)
                    response.raise_for_status()
                    
                    total_size = int(response.headers.get('content-length', 0))
                    downloaded = 0
                    
                    with open(file_path, 'wb') as f:
                        for chunk in response.iter_content(chunk_size=8192):
                            if chunk:
                                f.write(chunk)
                                downloaded += len(chunk)
                                
                                # 计算单文件进度 (0-50) + 总体进度 (0-50)
                                file_progress = int((downloaded / total_size) * 50) if total_size > 0 else 0
                                total_progress = int((index - 1) / total_images * 50)
                                combined_progress = total_progress + file_progress
                                
                                self.progress_bar.setValue(combined_progress)
                                QApplication.processEvents()
                    
                    success_count += 1
                    
                except Exception as e:
                    self.result_display.append(f"下载失败: {name} - {str(e)}")
                    if os.path.exists(file_path):
                        os.remove(file_path)
                
                # 更新总进度（确保即使出错也能继续）
                self.progress_bar.setValue(int(index / total_images * 100))
                QApplication.processEvents()
            
            # 下载完成
            self.progress_bar.setValue(100)
            result_msg = f"\n图片下载完成: 成功 {success_count}/{total_images}"
            if success_count < total_images:
                result_msg += " (部分图片下载失败)"
            self.result_display.append(result_msg)
            
        except Exception as e:
            self.result_display.show_error(f"图片下载出错: {str(e)}")
            self.progress_bar.reset()
        finally:
            # 下载完成后保持进度条显示2秒
            QTimer.singleShot(2000, self.progress_bar.reset)
      

      
        
    def handle_download123(self):
        """处理视频下载"""
        if not hasattr(self, 'current_video_info') or not self.current_video_info.get('download_url'):
            self.result_display.show_warning("没有可下载的视频或未获取下载链接")
            return
            
        # 让用户选择保存目录和文件名
        options = QFileDialog.Options()
        default_filename = f"{self.current_video_info.get('title', 'video')}.mp4"
        file_path, _ = QFileDialog.getSaveFileName(
            self, 
            "保存视频文件", 
            default_filename, 
            "MP4 Files (*.mp4);;All Files (*)", 
            options=options
        )
        
        if not file_path:
            return
            
        try:
            # 下载前准备
            self.result_display.append(f"\n开始下载视频到: {file_path}")

            self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: 2px solid #2e7d32;
                border-radius: 8px;
                text-align: center;
                background-color: #e8f5e9;
                height: 24px;
            }
            
            QProgressBar::chunk {
                background-color: #4caf50;
                border-radius: 6px;
                width: 10px;
            }
        """)
            
            # NEW: 更彻底的进度条初始化
            self.progress_bar.reset()
            self.progress_bar.setMinimum(0)
            self.progress_bar.setMaximum(100)
            self.progress_bar.setValue(0)
            self.progress_bar.setVisible(True)  # 确保可见
            self.progress_bar.repaint()  # 强制重绘
            
            # 开始下载
            response = requests.get(self.current_video_info['download_url'], stream=True)
            response.raise_for_status()
            
            total_size = int(response.headers.get('content-length', 0))
            downloaded = 0
            
            # NEW: 使用QApplication.processEvents()来强制UI更新
            from PyQt5.QtWidgets import QApplication
            
            # 写入文件
            with open(file_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)
                        downloaded += len(chunk)
                        
                        # 计算进度
                        progress = int((downloaded / total_size) * 100) if total_size > 0 else 0
                        
                        # 更新进度条
                        self.progress_bar.setValue(progress)
                        
                        # NEW: 强制处理UI事件
                        QApplication.processEvents()
            
            # 下载完成
            self.progress_bar.setValue(100)
            self.result_display.append(f"视频下载完成: {file_path}")
            
        except Exception as e:
            self.result_display.show_error(f"下载失败: {str(e)}")
            self.progress_bar.reset()
            if os.path.exists(file_path):
                os.remove(file_path)


    def _handle_api_fetch(self, video_url, video_type):
        """处理API请求逻辑"""
        # ... API请求实现 ...

      # ========== 新增方法：显示本地爬取结果 ==========
    def show_crawl_result(self, data):
        """显示爬取结果"""
        result = [
            f"=== {data['source']}爬取结果 ===",
            f"标题: {data['title']}",
            f"类型: {data['type']}",
            f"原始链接: {data['url']}",
            "\n下载链接:"
        ]
        
        if data.get('download_urls'):
            result.extend([f"{i+1}. {url}" for i, url in enumerate(data['download_urls'])])
        else:
            result.append("未找到下载链接")
        
        self.result_display.append("\n".join(result))
    
    def handle_clear(self):
        """清空输入和输出"""
        self.video_input.clear()
        self.result_display.clear()
        self.progress_bar.reset()